package com.meitianhui.convenitenbuy.module.mine.presenter;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

import com.google.gson.Gson;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseResponse;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.main.http.MainApiDataSource;
import com.meitianhui.convenitenbuy.module.mine.contract.UserInfoContract;
import com.meitianhui.convenitenbuy.module.mine.http.MineApiDataSource;
import com.meitianhui.convenitenbuy.module.mine.model.ConsumerInfo;
import com.meitianhui.convenitenbuy.module.mine.model.UserPhotoResponse;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.UserInfoActivity;
import com.meitianhui.convenitenbuy.util.PictureUtil;
import com.meitianhui.convenitenbuy.util.PreferenceUtils;
import com.meitianhui.convenitenbuy.widget.dialog.BottomMenuDialog;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;

/**
 * Created by amy on 2017/11/3.
 */

public class UserInfoPresenter implements UserInfoContract.Presenter {

    private UserInfoContract.View mView;
    private UserInfoActivity mContext;
    /* 照相机缓存头像名称 */
    protected static final String IMAGE_FILE_NAME_TEMP = "temp_faceImage.jpg";
    protected static final String IMAGE_FILE_NEW_PHOTO = "temp_faceImage.png";
    private File mTempFile;
    private String mDoc_path;

    public UserInfoPresenter(UserInfoActivity view, UserInfoActivity context) {
        this.mView = view;
        this.mContext = context;
    }

    public void openCamera() {
        Matisse.from(mContext)
                .choose(MimeType.ofAll()) // 选择 mime 的类型
                .countable(true) // 显示选择的数量
                .capture(true)  // 开启相机，和 captureStrategy 一并使用否则报错
                .captureStrategy(new CaptureStrategy(true, "com.meitianhui.convenitenbuy.FileProvider")) // 拍照的图片路径
                .theme(R.style.Matisse_Zhihu) // 黑色背景
                .maxSelectable(1) // 图片选择的最多数量
                .gridExpectedSize(mContext.getResources().getDimensionPixelSize(R.dimen.dp_120)) // 列表中显示的图片大小
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                .forResult(BottomMenuDialog.CAMER_CODE); // 设置作为标记的请求码，返回图片时使用

        /*
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
        mTempFile = new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME_TEMP);
        // 判断版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {   //如果在Android7.0以上,使用FileProvider获取Uri
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(mContext, "com.meitianhui.convenitenbuy.FileProvider", mTempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {    //否则使用Uri.fromFile(file)方法获取Uri
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempFile));
        }
        intent.putExtra(Constants.INTENT_FLAG_SOURCE, true);
        mContext.startActivityForResult(intent, BottomMenuDialog.CAMER_CODE);
        */
        mView.dismissDialog();
    }

    public void openAlbum() {
        Matisse.from(mContext)
                .choose(MimeType.ofAll(), false) // 选择 mime 的类型
                .countable(true)
                .maxSelectable(1) // 图片选择的最多数量
                .gridExpectedSize(mContext.getResources().getDimensionPixelSize(R.dimen.dp_120))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .theme(R.style.Matisse_Zhihu) // 黑色背景
                .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                .forResult(BottomMenuDialog.LOCAL_CODE); // 设置作为标记的请求码
        /*
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image*//*");
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
        intent.putExtra(Constants.INTENT_FLAG_SOURCE, true);
        mContext.startActivityForResult(intent, BottomMenuDialog.LOCAL_CODE);
        */
        mView.dismissDialog();
    }

    public void dealWithPicture(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case BottomMenuDialog.CAMER_CODE://相机
                    //用相机返回的照片去调用剪裁也需要对Uri进行处理
                    /*
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri contentUri = FileProvider.getUriForFile(mContext, "com.meitianhui.convenitenbuy.FileProvider", mTempFile);
                        PictureUtil.startPhotoZoom(mContext, contentUri);
                    } else {
                        PictureUtil.startPhotoZoom(mContext, Uri.fromFile(mTempFile));
                    }
                    */
                    List<Uri> urisList = Matisse.obtainResult(data);
                    Uri uri = urisList.get(0);
                    // if (SystemUtils.isMIUI()){
                    /*
                        //如果是小米手机
                        String scheme = uri.getScheme();
                        String imagePath = "";
                        if("content".equals(scheme)){
                            String[] filePathColumns = {MediaStore.Images.Media.DATA};
                            Cursor c = mContext.getContentResolver().query(uri, filePathColumns, null, null, null);
                            c.moveToFirst();
                            int columnIndex = c.getColumnIndex(filePathColumns[0]);
                            imagePath = c.getString(columnIndex);
                            c.close();
                        }else if("file".equals(scheme)){//小米4选择云相册中的图片是根据此方法获得路径
                            imagePath = uri.getPath();
                        } */

                    // PictureUtil.startPhotoZoom(mContext,uri);
                    PictureUtil.startPhotoZoom(mContext, uri);
                    break;
                case BottomMenuDialog.LOCAL_CODE:  //相册
                    PictureUtil.startPhotoZoom(mContext, Matisse.obtainResult(data).get(0));
                    break;
                case BottomMenuDialog.REQUEST_CODE:
                    // 保存截取后的图片
                    if (data != null) {
                        Bundle extras = data.getExtras();
                        if (extras != null) {
                            Bitmap photo = extras.getParcelable("data");
                            savePhoto(photo);
                        }
                    }
                    break;
            }
        }
    }

    private void savePhoto(Bitmap photo) {
        // 将bitmap类型转化成file类型
        File file = new File(Environment.getExternalStorageDirectory().getPath(), IMAGE_FILE_NEW_PHOTO);
        BufferedOutputStream outputStream = null;
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(file));
            photo.compress(Bitmap.CompressFormat.PNG, 10, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 保存图片至服务器
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part multpartBody =
                MultipartBody.Part.createFormData("up_load_file", IMAGE_FILE_NEW_PHOTO, requestBody);

        MineApiDataSource.getInstance()
                .uploadHeadImg(InfoProvider.getAppToken(App.getInstance()),
                        "oss_community", "png", "meitianhuiheadImg.png", multpartBody)
                .subscribe(new ResponseObserver<UserPhotoResponse>(App.getInstance()) {
                    @Override
                    public void onSuccess(UserPhotoResponse response) {
                        HashMap<String, String> data = response.data;
                        String doc_id = data.get("doc_id");
                        mDoc_path = data.get("doc_path");
                        mView.setUserPhoto(mDoc_path, doc_id);
                        upDateLocalConsumer(mDoc_path, Constants.CLICK_USER_PHOTO);
                    }
                });
    }

    public void upLoadUserInfo(String nickName, String userSex, String userBirthday,
                               String userName, String userPhotoPath) {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", InfoProvider.getUserToken(App.getInstance()).getMember_id());
        map.put("nick_name", nickName);
        map.put("sex_key", userSex);
        map.put("birthday", userBirthday);
        map.put("full_name", userName);
        map.put("head_pic_path", userPhotoPath);
        map.put("area_id", "");
        map.put("address", "");

        MineApiDataSource.getInstance()
                .upDateUserInfo(InfoProvider.getAppToken(App.getInstance()),
                        "member.consumerInfoUpdate", new Gson().toJson(map))
                .subscribe(new ResponseObserver<Object>(App.getInstance()) {
                    @Override
                    public void onSuccess(Object o) {
                    }
                });
    }

    @Override
    public String stringFilter(String trim) {
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(trim);
        String match = m.replaceAll("").trim();
        match = match.replaceAll(" ", "");
        return match;
    }

    /**
     * 跟新本地存储的consumer对象
     */
    @Override
    public void upDateLocalConsumer(String newValue, int clickItem) {
        ConsumerInfo consumerInfo = InfoProvider.getConsumerInfo(App.getInstance());
        if (clickItem == Constants.CLICK_USER_PHOTO) {
            consumerInfo.setHead_pic_path(newValue);
        } else if (clickItem == Constants.CLICK_USER_BIRTHDAY) {
            consumerInfo.setBirthday(newValue);
        } else if (clickItem == Constants.CLICK_USER_NAME) {
            consumerInfo.setFull_name(newValue);
        } else if (clickItem == Constants.CLICK_USER_NICKNAME) {
            consumerInfo.setNick_name(newValue);
        } else if (clickItem == Constants.CLICK_USER_SEX) {
            consumerInfo.setSex_key(newValue);
        }
        PreferenceUtils.saveObject(mContext, Constants.CONSUMER_INFO, consumerInfo);
        mView.upDateUserInfo();
    }

    @Override
    public void getLatestConsumerInfo() {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", InfoProvider.getUserToken(mContext).getMember_id());
        String json = new Gson().toJson(map);

        MainApiDataSource.getInstance()
                .getConsumerInfo(InfoProvider.getAppToken(mContext), "member.consumerFind", json)
                .subscribe(new ResponseObserver<BaseResponse<ConsumerInfo>>(mContext) {
                    @Override
                    public void onSuccess(BaseResponse<ConsumerInfo> response) {
                        mView.getLatestConsumerInfoSucc(response.data);
                    }
                });
    }

    @Override
    public void attachView(Object view) {
    }

    @Override
    public void detachView() {
    }

}
